package com.whp.bean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionVisitor;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.util.StringValueResolver;

import java.util.HashSet;
import java.util.Set;

/**
 * @author wanghp
 * @version 1.0
 * @date 2020/8/12 17:18
 */

public class ObscenityRemovingBeanFactoryProcessor implements BeanFactoryPostProcessor {

	private Set<String> Obscenities;

	public ObscenityRemovingBeanFactoryProcessor() {
		this.Obscenities = new HashSet<>();
	}

	public void setObscenities(Set<String> obscenities) {
		this.Obscenities.clear();
		for (String obscenity : obscenities) {
			this.Obscenities.add(obscenity.toUpperCase());
		}

	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
		for (String beanDefinitionName : beanDefinitionNames) {
			BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanDefinitionName);
			StringValueResolver stringValueResolver = new StringValueResolver() {
				@Override
				public String resolveStringValue(String strVal) {
					if (isObscenity(strVal)) {
						return "*******";
					}
					return strVal;
				}


			};
			BeanDefinitionVisitor beanDefinitionVisitor = new BeanDefinitionVisitor(stringValueResolver);
			beanDefinitionVisitor.visitBeanDefinition(beanDefinition);
		}
	}

	private boolean isObscenity(String strVal) {
		String upperCase = strVal.toUpperCase();
		return this.Obscenities.contains(upperCase);
	}
}
